package com.ice.base.aop;

import com.ice.base.model.SysLoginLogModel;
import com.ice.base.model.SysLoginModel;
import com.ice.base.service.SysLoginLogService;
import com.ice.base.service.SysOperationLogService;
import com.ice.base.util.BaseUtil;
import com.ice.base.util.LogUtils;
import com.ice.base.util.ip.AddressUtils;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;


/**
 * 本身作为方法的切面，临时改为登录日志
 */
@Slf4j
@Component
@Aspect
public class ControllerAspect {


    @Resource
    private SysLoginLogService sysLoginLogService;

    @Pointcut("@annotation(ControllerMethodLog)")
    public void controllerMethodLog() {
    }


/*    @Before("execution(* com.ice.body.business.controller.OrderController.test(..))")
    public void beforeTest(JoinPoint joinPoint) {
        Object[] obj = joinPoint.getArgs();
        System.out.println("joinPoint = " + joinPoint);
        System.out.println("他来了！");
    }*/


    @Before(value = "controllerMethodLog()")
    public void beforeController(JoinPoint joinPoint) {
        Object[] obj = joinPoint.getArgs();
        Signature signature = joinPoint.getSignature();
        if(signature.getName().equals("doLogin")){
        }else{
            signature.getDeclaringType();
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                HttpServletRequest request = attributes.getRequest();
            }
        }
    }


    @AfterReturning(value = "controllerMethodLog()", returning = "result")
    public void afterReturnControllerMethodLog(JoinPoint joinPoint, Object result) {
        String targetName = joinPoint.getTarget().getClass().getName();
        String methodName = joinPoint.getSignature().getName();

        Object[] arguments = joinPoint.getArgs();
        Class targetClass = null;
        try {
            targetClass = Class.forName(targetName);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        if (targetClass != null) {
            Method[] methods = targetClass.getMethods();
            String description = null;
            for (Method method : methods) {
                if (method.getName().equals(methodName)) {
                    if (method.getParameterTypes().length == arguments.length) {
                        description = method.getAnnotation(ControllerMethodLog.class).remark();
                        log.info(method.getName()+","+description+",结果："+result.toString());
                        break;
                    }
                }
            }
            if (description != null) {
                Subject subject = SecurityUtils.getSubject();
                if (subject != null) {
                    if(subject.getPrincipals()!=null){
                        SysLoginModel sysLoginModel = (SysLoginModel) subject.getPrincipals().getPrimaryPrincipal();
                        if (sysLoginModel != null) {

                            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
                            final UserAgent userAgent = UserAgent.parseUserAgentString(attributes.getRequest().getHeader("User-Agent"));
                            final String ip = BaseUtil.getIPAddress(attributes.getRequest());


                            String address = AddressUtils.getRealAddressByIP(ip);
                            StringBuilder s = new StringBuilder();
                            s.append(LogUtils.getBlock(ip));
                            s.append(address);
                            s.append(LogUtils.getBlock(sysLoginModel.getRealName()));
                            s.append(LogUtils.getBlock(1));
                            s.append(LogUtils.getBlock("登录系统"));
                            // 获取客户端操作系统
                            String os = userAgent.getOperatingSystem().getName();
                            // 获取客户端浏览器
                            String browser = userAgent.getBrowser().getName();

                            SysLoginLogModel login = new SysLoginLogModel();
                            login.setSll_login_id(sysLoginModel.getId().toString());
                            login.setSll_login_ip(ip);
                            login.setCreateTime(new Date());
                            login.setOs(os);
                            login.setBrowser(browser);
                            login.setLogin_location(address);
                            login.setLoginUser(sysLoginModel.getUserName());
                            sysLoginLogService.insert(login);
                          /*  SysOperationLogModel sysOperationLogModel = new SysOperationLogModel();
                            sysOperationLogModel.init(sysOperationLogModel);
                            sysOperationLogModel.setSol_des(description);
                            sysOperationLogModel.setSol_login_id(sysLoginModel.getId());
                            sysOperationLogService.insert(sysOperationLogModel);*/
                        }
                    }
                }
            }
        }
    }
}
